package mysql

import (
	"fmt"
	"gorm.io/gorm"
	"strconv"
)

type Video struct {
	gorm.Model
	UserId int    `json:"userId" gorm:"type:int(10);not null;comment:'用户编号'"`
	Name   string `json:"name" gorm:"type:varchar(20);not null;comment:'视频名称'"`
	Time   string `json:"time" gorm:"type:varchar(50);not null;comment:'视频时长'"`
	Intro  string `json:"intro" gorm:"type:varchar(200);not null;comment:'视频简介'"`
	URL    string `json:"URL" gorm:"type:varchar(255);not null;comment:'视频'"`
}

func (v *Video) Create() error {
	return DB.Model(&Video{}).Create(&v).Error
}

func List(keyWord string, page, pageSize int) ([]*Video, error) {
	query := DB.Model(&Video{})
	var video []*Video
	if keyWord != "" {
		err = query.Where("name=?", keyWord).Scopes(Paginate(page, pageSize)).Find(&video).Error
		if err != nil {
			return nil, err
		}
		return video, nil
	}
	err = query.Scopes(Paginate(page, pageSize)).Find(&video).Error
	if err != nil {
		return nil, err
	}
	return video, nil
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		page, _ = strconv.Atoi(strconv.Itoa(page))
		if page <= 0 {
			page = 1
		}

		pageSize, _ = strconv.Atoi(strconv.Itoa(pageSize))
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

func Delete(videoId, userId int) error {
	fmt.Println(videoId, userId)
	return DB.Model(&Video{}).Where("user_id=? and id=?", userId, videoId).Delete(&Video{}).Error
}

func Update(videoId, userId int, video *Video) error {
	return DB.Model(&Video{}).Where("user_id=? and id=?", userId, videoId).Updates(&video).Error
}
